/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

var ajax = {
    post: function (settings) {
        settings.method = "POST";
        return this.call(settings);
    },
    call: function (settings) {
        var method = settings.method;
        var xhr = new XMLHttpRequest();
        var url = settings.url;
        var param;
        if (!settings.param)
            settings.param = {};
        if (settings.xml) {
            settings.param.xml = new XMLSerializer().serializeToString(settings.xml);
        }

        if (settings.file) {
            param = new FormData();
            param.append('file', settings.file);
        } else {
            param = this.generateParam(settings.param);
        }
        xhr.onreadystatechange = this.callback(xhr, settings);
        xhr.open(method, url, true);
        if (!settings.file)
            xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        xhr.send(param);
    },

    generateParam: function (param) {
        var genParam = "";
        var symbol = "";
        for (var k in param) {
            var value = param[k];
            if (!(value instanceof Function)) {
                if (typeof(value) === "undefined" || value === null) {
                    value = "";
                } else if (!(value instanceof Array)) {
                    value = [value];
                }

                for (var n = 0; n < value.length; n++) {
                    if (param[k] !== null) {
                        genParam += (symbol + k + "=" + this.encodeParam(value[n]));
                    } else {
                        genParam += (symbol + k);
                    }
                    symbol = "&";
                }
                symbol = "&";
            }
        }
        return genParam;
    },

    encodeParam: function (param) {
        var result = null;
        if (typeof(param) === "string") {
            result = param;
        } else {
            result = JSON.stringify(param);
        }
        result = encodeURIComponent(result);
        return result;
    },

    callback: function (xhr, settings) {
        return function () {
            var result;
            clearTimeout(xhr.requestTimeout);
            if (xhr.readyState === 4) {
                var status = xhr.status;
                if (status === 0) {
                    if (settings.abort) {
                        settings.abort(xhr);
                    } else if (settings.failure) {
                        settings.failure(xhr);
                    }

                } else if (status === 200) {
                    if (xhr.responseText) {
                        try {
                            var parser = new DOMParser();
                            result = parser.parseFromString(decodeURIComponent(xhr.responseText), "text/xml");
                        } catch (e) {
                            throw e;
                        }
                    } else if (xhr.responseXML) {
                        result = xhr.responseXML;
                    }

                    if (settings.success) {
                        settings.success(result, xhr);
                    }

                } else {
                    if (settings.error) {
                        settings.error(result, xhr);
                    } else if (settings.failure) {
                        settings.failure(xhr);
                    }
                }
            }
        };
    }
};

var xmlUtils = {

    getURLParameter: function (name, link) {
        var url = location.search;
        if (link) {
            url = link;
        }
        return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(url) || [, ""])[1].replace(/\+/g, '%20')) || null
    },

    loadXML: function (path) {
        xhttp = new XMLHttpRequest();
        xhttp.open("GET", path, false);
        xhttp.send();
        return xhttp.responseXML;
    },

    transformXSL: function (xmlDoc, xslURl, param) {
        var xslDoc = this.loadXML(xslURl);
        this.Processor = new XSLTProcessor();
        this.Processor.importStylesheet(xslDoc, "text/xml");
        if (param instanceof Array) {
            for (var i = 0; i < param.length; i++) {
                var temp = param[i];
                this.Processor.setParameter(null, temp.key, temp.value);
            }

        }
        return this.Processor.transformToFragment(xmlDoc, document);
    },

    objToXML: function (obj, root) {
        var xml = document.createElement(root);

        function walk(obj, currentNode) {
            for (var property in obj) {
                if (typeof(obj[property]) === "string" || typeof(obj[property]) === "number") {
                    var node = document.createElement(property);
                    node.innerText = obj[property];
                    currentNode.appendChild(node);
                }

                else if (typeof(obj[property]) === "object" && obj[property]) {
                    var node = document.createElement(property);
                    var list = obj[property];
                    for (var item in list) {
                        var warpper = document.createElement("tag");
                        node.appendChild(walk(list[item], warpper));
                        currentNode.appendChild(node);
                    }
                }
            }
            return currentNode;
        }

        walk(obj, xml);
        return xml;
    },

    XMLtoObj: function (nodes) {
        var obj = {};
        if (nodes.nodeType && nodes.nodeType === nodes.DOCUMENT_NODE) {
            obj = this.XMLtoObj(nodes.childNodes);
        }
        for (var i = 0; i < nodes.length; i++) {
            var node = nodes[i];
            if (node.nodeType === node.ELEMENT_NODE) {
                if (obj.hasOwnProperty(node.localName)) {
                    if (!(obj[node.localName] instanceof Array)) {
                        var array = [obj[node.localName]];
                        obj[node.localName] = array;
                    }
                    obj[node.localName].push(this.XMLtoObj(node.childNodes));
                } else {
                    obj[node.localName] = this.XMLtoObj(node.childNodes);
                }
            } else if (node.nodeType === node.TEXT_NODE && !node.nextSibling) {
                if (trim(node.nodeValue) != "") {
                    return node.nodeValue;
                }
            }
        }
        return Object.keys(obj).length === 0 ? "" : obj;
    },

    generateCurrentTime: function () {
        var d = new Date();
        return "" + d.getDate() + (d.getMonth() + 1) + d.getFullYear() + d.getHours() + d.getMinutes() + d.getSeconds();
    },

    getNodeWithData: function (node) {
        if (node === null) {
            return;
        }

        if (node && node.attributes && node.attributes['data']) {
            return node.attributes['data'].value;
        }

        return this.getNodeWithData(node.parentNode);
    },

    getValue: function (node) {
        var obj = {};

        function walk(node) {
            var child, next;
            switch (node.nodeType) {
                case 3: // Text node
                    if (node.textContent.trim() && node.parentNode.getAttribute("name"))
                        obj[node.parentNode.getAttribute("name")] = node.textContent.replace(/[\r\n]/g, "").replace(/\s+/g, " ").trim();
                    break;
                case 1: // Element node
                case 9: // Document node
                    if (node.getAttribute("name")) {
                        if (node.nodeName === "INPUT" || node.nodeName === "TEXTAREA") {
                            obj[node.getAttribute("name")] = node.value;
                        } else if (node.nodeName === "SELECT") {
                            obj[node.getAttribute("name")] = node.options[node.selectedIndex].value;
                            break;
                        } else if (node.nodeName === "IMG") {
                            obj[node.getAttribute("name")] = node.src;
                            break;
                        }
                    }
                    child = node.firstChild;
                    while (child) {
                        next = child.nextSibling;
                        walk(child);
                        child = next;
                    }
                    break;
            }
        }

        walk(node);
        return obj;
    },

    setValue: function (node, obj) {
        function walk(node) {
            var child, next;
            switch (node.nodeType) {
                case 3: // Text node
                    if (node.parentNode.getAttribute("name") && (obj[node.parentNode.getAttribute("name")]
                        && (obj[node.parentNode.getAttribute("name")]) != "" || obj[node.parentNode.getAttribute("name")] == 0)) {
                        node.textContent = obj[node.parentNode.getAttribute("name")];
                    }
                    break;
                case 1: // Element node
                case 9: // Document node
                    if (node.getAttribute("name") && (obj[node.getAttribute("name")] &&
                        (obj[node.getAttribute("name")] != "") || obj[node.getAttribute("name")] == 0)) {
                        if (node.nodeName === "INPUT" || node.nodeName === "TEXTAREA") {
                            node.value = obj[node.getAttribute("name")];
                        } else if (node.nodeName === "SELECT") {
                            node.value = obj[node.getAttribute("name")];
                            break;
                        } else if (node.nodeName === "IMG" && obj[node.getAttribute("name")] != "") {
                            node.src = obj[node.getAttribute("name")];
                            break;
                        } else if (!node.firstChild) {
                            node.textContent = obj[node.getAttribute("name")];
                        }
                    }
                    child = node.firstChild;
                    while (child) {
                        next = child.nextSibling;
                        walk(child);
                        child = next;
                    }
                    break;
            }
        }

        walk(node);
        return obj;
    },

    centeredPopup: function (node) {
        node.style.position = "absolute";
        node.style.left = "50%";
        node.style.top = "50%";
        node.style.marginLeft = (-node.offsetWidth / 2) + "px";
        node.style.marginTop = (-node.offsetHeight / 2) + "px";
    },

    showTimeOutPopup: function (msg, time, callback) {
        var defaultTime = 3000;
        if (time) defaultTime = time;
        $id("info-popup-timeout").getElementsByClassName("message")[0].innerText = msg;
        removeClass($id("info-popup-timeout"), "hidden");
        removeClass($id("info-popup-wrapper"), "hidden");
        xmlUtils.centeredPopup($id("info-popup-timeout"));
        setTimeout(function () {
            addClass($id("info-popup-timeout"), "hidden");
            addClass($id("info-popup-wrapper"), "hidden");
            if (callback) callback();
        }, defaultTime);
    },

    closePopup: function (node) {
        var parent = getParentNode(node, "popup");
        addClass(parent, "hidden");
        addClass($id("info-popup-wrapper"), "hidden");
    }
};

function $id(id) {
    return document.getElementById(id);
}

function trim(string) {
    return string.replace(/[^a-zA-Z:0-9,]/g, "");
}

function $class(className) {
    return document.getElementsByClassName(className);
}

function hasClass(ele, cls) {
    return ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'));
}

function addClass(ele, cls) {
    if (!this.hasClass(ele, cls))
        ele.className += " " + cls;
}

function removeClass(ele, cls) {
    if (this.hasClass(ele, cls)) {
        var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)');
        ele.className = ele.className.replace(reg, ' ');
    }
}

function getParentNode(node, data) {
    if (node === null) {
        return;
    }
    if (node && node.attributes && node.attributes['data'] && node.attributes['data'].value == data) {
        return node;
    }
    return this.getParentNode(node.parentNode, data);
}

